package com.zp.base.admin.controller;

import com.zp.base.admin.common.utils.CaptchaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ZhangPeng
 * @email zhangpeng98@aliyun.com
 * @create 2021-02-28 15:27
 *
 * 验证码生成控制器
 */
@RequestMapping("/captcha")
@Controller
@Slf4j
public class CaptchaController {

    /**
     * 通用验证码生成器
     * 获取验证码图片
     */
    @RequestMapping("/generateCaptcha")
    public void generateCaptcha(@RequestParam(name = "vl", defaultValue = "4") int vCodeLen,  //验证码长度
                                @RequestParam(name = "fs", defaultValue = "21") int fontSize,  //验证码图片字体大小
                                @RequestParam(name = "w", defaultValue = "98") int width,  //验证码图片宽度
                                @RequestParam(name = "h", defaultValue = "33") int height,  //验证码图片高度
                                @RequestParam(name = "method", defaultValue = "adminLogin") String method,  //生成该验证码的功能模块，默认后台登录  adminLogin
                                HttpServletRequest request,
                                HttpServletResponse response){
        CaptchaUtil captchaUtil = new CaptchaUtil(vCodeLen, fontSize, width, height);
        String generatorVCode = captchaUtil.generatorVCode();
        log.info("生成的验证码：{}, 调用的method: {}", generatorVCode, method);
        //将验证码放入session，用于验证
        request.getSession().setAttribute(method, generatorVCode);

        try {
            ImageIO.write(captchaUtil.generatorRotateVCodeImage(generatorVCode, true), "jpg", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
